<template>
  <div class="permission-list">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="菜单" :value="1" />
            <el-option label="按钮" :value="2" />
            <el-option label="接口" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="searchPermissions">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-button type="primary" :icon="Plus" @click="openAddDialog">新增权限</el-button>
      <el-button type="danger" :icon="Delete" @click="batchDelete" :disabled="selectedPermissions.length === 0">
        批量删除
      </el-button>
    </el-card>

    <!-- 权限列表 -->
    <el-card>
      <el-table
        :data="permissionList"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="权限ID" width="80" />
        <el-table-column prop="name" label="权限名称" />
        <el-table-column prop="code" label="权限编码" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" />
        <el-table-column prop="method" label="请求方法" />
        <el-table-column prop="icon" label="图标" />
        <el-table-column prop="sort" label="排序" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="deletePermission(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增权限' : '编辑权限'"
      width="600px"
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="permissionTreeData"
            :props="{ label: 'name', children: 'children', value: 'id' }"
            placeholder="请选择上级权限"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option label="菜单" :value="1" />
            <el-option label="按钮" :value="2" />
            <el-option label="接口" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入请求路径" />
        </el-form-item>
        <el-form-item label="请求方法" prop="method">
          <el-select v-model="form.method" placeholder="请选择请求方法" style="width: 100%" clearable>
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
            <el-option label="PATCH" value="PATCH" />
          </el-select>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="savePermission" :loading="saveLoading">
          {{ dialogType === 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { 
  getPermissionPage, 
  getPermissionById, 
  saveOrUpdatePermission, 
  deletePermissions,
  getPermissionList 
} from '@/api/system'

// 权限类型映射
const permissionTypes = {
  1: '菜单',
  2: '按钮',
  3: '接口'
}

// 搜索表单
const searchForm = ref({
  name: '',
  code: '',
  type: ''
})

// 权限列表数据
const permissionList = ref([])
const loading = ref(false)
const selectedPermissions = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框参数
const dialogVisible = ref(false)
const dialogType = ref('add')
const saveLoading = ref(false)

// 权限树数据（用于上级权限选择）
const permissionTreeData = ref([])

// 表单数据
const form = ref({
  id: '',
  parentId: '',
  name: '',
  code: '',
  type: 1,
  path: '',
  method: '',
  icon: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z_:]+$/, message: '只能包含字母、下划线和冒号', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  path: [
    { max: 200, message: '路径不能超过200个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

const formRef = ref()

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type) => {
  return permissionTypes[type] || '未知'
}

// 加载权限列表
const loadPermissionList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    }
    const res = await getPermissionPage(params)
    permissionList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取权限列表失败')
    console.error('Failed to load permission list:', error)
  } finally {
    loading.value = false
  }
}

// 加载权限树
const loadPermissionTree = async () => {
  try {
    const permissions = await getPermissionList()
    permissionTreeData.value = buildPermissionTree(permissions)
  } catch (error) {
    ElMessage.error('加载权限树失败')
  }
}

// 构建权限树
const buildPermissionTree = (permissions) => {
  const tree = []
  const map = {}
  
  // 创建映射
  permissions.forEach(permission => {
    map[permission.id] = { ...permission, children: [] }
  })
  
  // 构建树结构
  permissions.forEach(permission => {
    if (permission.parentId === '0' || !permission.parentId) {
      tree.push(map[permission.id])
    } else if (map[permission.parentId]) {
      map[permission.parentId].children.push(map[permission.id])
    }
  })
  
  return tree
}

// 搜索权限
const searchPermissions = () => {
  currentPage.value = 1
  loadPermissionList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    code: '',
    type: ''
  }
  currentPage.value = 1
  loadPermissionList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedPermissions.value = val
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadPermissionList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadPermissionList()
}

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    await saveOrUpdatePermission({
      ...row,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    parentId: '',
    name: '',
    code: '',
    type: 1,
    path: '',
    method: '',
    icon: '',
    sort: 0,
    status: 1
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  try {
    const res = await getPermissionById(row.id)
    form.value = { ...res }
    dialogType.value = 'edit'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取权限详情失败')
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 保存权限
const savePermission = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true
    
    await saveOrUpdatePermission(form.value)
    ElMessage.success(dialogType.value === 'add' ? '新增权限成功' : '更新权限成功')
    closeDialog()
    loadPermissionList()
    loadPermissionTree()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(dialogType.value === 'add' ? '新增权限失败' : '更新权限失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 删除权限
const deletePermission = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该权限吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deletePermissions([row.id])
    ElMessage.success('删除权限成功')
    loadPermissionList()
    loadPermissionTree()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除权限失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedPermissions.value.length === 0) {
    ElMessage.warning('请选择要删除的权限')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedPermissions.value.length} 个权限吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedPermissions.value.map(item => item.id)
    await deletePermissions(ids)
    ElMessage.success('批量删除权限成功')
    loadPermissionList()
    loadPermissionTree()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除权限失败')
    }
  }
}

// 初始化加载
onMounted(() => {
  loadPermissionList()
  loadPermissionTree()
})
</script>

<style scoped>
.permission-list {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
}
</style>